package com.tianji.promotion.aspect;

import com.tianji.promotion.annotation.Lock;
import com.tianji.promotion.factory.MyLockFactory;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

/**
 * <p>
 * 分布式锁AOP增强
 * </p>
 *
 * @author lcm
 * @since 2023-08-04
 */
@Aspect
@Component
@RequiredArgsConstructor
public class LockedAspect implements Ordered {
    private final MyLockFactory lockFactory;

    @Around("@annotation(lock)")
    public Object tryLock(ProceedingJoinPoint pjp, Lock lock) throws Throwable {
        //使用策略模式加以改造
        RLock rlock = lockFactory.getLock(lock.lockType(), lock.name());
        boolean isLock = lock.lockStrategy().tryLock(rlock, lock);
        if(!isLock){
            return null;
        }

        try {
            // 3.2.成功，执行业务
            return pjp.proceed();
        } finally {
            // 4.释放锁
            rlock.unlock();
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
